// 显示器管理组合式函数
import { ref } from 'vue'

interface MonitorInfo {
  name: string
  position: { x: number; y: number }
  size: { width: number; height: number }
  scaleFactor: number
}

interface MonitorCache {
  monitors: MonitorInfo[]
  timestamp: number
  isValid: boolean
}

export function useMonitorManager() {
  // 显示器信息缓存
  const monitorCache = ref<MonitorCache>({
    monitors: [],
    timestamp: 0,
    isValid: false
  })

  // 缓存有效期（5分钟）
  const CACHE_DURATION = 5 * 60 * 1000

  // 初始化显示器信息
  const initializeMonitors = async (): Promise<void> => {
    try {
      const { availableMonitors } = await import('@tauri-apps/api/window')
      const monitors = await availableMonitors()

      monitorCache.value = {
        monitors,
        timestamp: Date.now(),
        isValid: true
      }
    } catch (error) {
      monitorCache.value.isValid = false
    }
  }

  // 获取缓存的显示器信息
  const getMonitors = async (): Promise<MonitorInfo[]> => {
    const now = Date.now()

    // 检查缓存是否有效
    if (!monitorCache.value.isValid ||
      (now - monitorCache.value.timestamp) > CACHE_DURATION) {
      await initializeMonitors()
    }

    return monitorCache.value.monitors
  }

  // 根据显示器标识找到目标显示器
  const findMonitorById = async (monitorId: string): Promise<MonitorInfo | null> => {
    const monitors = await getMonitors()
    return monitors.find(m => {
      const id = `${m.position.x}_${m.position.y}_${m.size.width}_${m.size.height}`
      return id === monitorId
    }) || null
  }

  // 根据显示器编号找到目标显示器
  const findMonitorByIndex = async (screenNumber: number): Promise<MonitorInfo | null> => {
    const monitors = await getMonitors()
    return monitors[screenNumber - 1] || null
  }

  // 根据显示器名称找到目标显示器
  const findMonitorByName = async (monitorName: string): Promise<MonitorInfo | null> => {
    const monitors = await getMonitors()
    return monitors.find(m => m.name === monitorName) || null
  }

  // 根据坐标找到对应的显示器
  const findMonitorByCoordinates = async (x: number, y: number): Promise<MonitorInfo | null> => {
    const monitors = await getMonitors()
    return monitors.find(m => {
      const inXRange = x >= m.position.x && x < (m.position.x + m.size.width)
      const inYRange = y >= m.position.y && y < (m.position.y + m.size.height)
      return inXRange && inYRange
    }) || null
  }

  // 智能匹配显示器
  const matchMonitor = async (config: {
    monitorId?: string
    monitorName?: string
    screenNumber?: number
    x?: number
    y?: number
  }): Promise<{
    monitor: MonitorInfo | null
    method: string
  }> => {

    // 优先使用显示器名称匹配
    if (config.monitorName) {
      const monitor = await findMonitorByName(config.monitorName)
      if (monitor) {
        return { monitor, method: 'monitorName' }
      }
    }

    // 使用显示器标识匹配
    if (config.monitorId) {
      const monitor = await findMonitorById(config.monitorId)
      if (monitor) {
        return { monitor, method: 'monitorId' }
      }
    }

    // 使用显示器编号匹配
    if (config.screenNumber && config.screenNumber > 0) {
      const monitor = await findMonitorByIndex(config.screenNumber)
      if (monitor) {
        return { monitor, method: 'screenNumber' }
      }
    }

    // 使用坐标范围匹配
    if (config.x !== undefined && config.y !== undefined) {
      const monitor = await findMonitorByCoordinates(config.x, config.y)
      if (monitor) {
        return { monitor, method: 'coordinates' }
      }
    }

    return { monitor: null, method: 'none' }
  }

  // 计算窗口在目标显示器上的位置
  const calculateWindowPosition = (
    targetMonitor: MonitorInfo,
    originalX: number,
    originalY: number,
    originalMonitorPosition?: { x: number; y: number },
    windowWidth: number = 200,
    windowHeight: number = 800
  ): { x: number; y: number } => {
    let relativeX, relativeY

    if (originalMonitorPosition) {
      // 使用保存的显示器位置信息计算相对坐标
      relativeX = originalX - originalMonitorPosition.x
      relativeY = originalY - originalMonitorPosition.y
    } else {
      // 假设原坐标是相对于主显示器的
      const primaryMonitor = monitorCache.value.monitors[0]
      if (primaryMonitor) {
        relativeX = originalX - primaryMonitor.position.x
        relativeY = originalY - primaryMonitor.position.y
      } else {
        relativeX = originalX
        relativeY = originalY
      }
    }

    // 确保相对坐标在合理范围内
    relativeX = Math.max(0, Math.min(relativeX, targetMonitor.size.width - windowWidth))
    relativeY = Math.max(0, Math.min(relativeY, targetMonitor.size.height - windowHeight))

    // 计算最终位置
    return {
      x: targetMonitor.position.x + relativeX,
      y: targetMonitor.position.y + relativeY
    }
  }

  // 获取显示器数量
  const getMonitorCount = async (): Promise<number> => {
    const monitors = await getMonitors()
    return monitors.length
  }

  // 获取主显示器
  const getPrimaryMonitor = async (): Promise<MonitorInfo | null> => {
    const monitors = await getMonitors()
    return monitors[0] || null
  }

  // 刷新显示器信息
  const refreshMonitors = async (): Promise<void> => {
    monitorCache.value.isValid = false
    await initializeMonitors()
  }

  return {
    // 状态
    monitorCache,

    // 核心方法
    initializeMonitors,
    getMonitors,
    matchMonitor,
    calculateWindowPosition,

    // 查找方法
    findMonitorById,
    findMonitorByIndex,
    findMonitorByName,
    findMonitorByCoordinates,

    // 工具方法
    getMonitorCount,
    getPrimaryMonitor,
    refreshMonitors
  }
}
